package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.MyBaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;


    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        Long id = MyBaseContext.getId();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(null != id, AddressBook::getUserId, id).orderByDesc(AddressBook::getUpdateTime);

        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);
    }

    @PostMapping
    public R save(@RequestBody AddressBook addressBook) {
        Long id = MyBaseContext.getId();
        addressBook.setUserId(id);
        boolean b = addressBookService.save(addressBook);
        if (b) {
            return R.success(addressBook);
        }
        return R.error("保存失败");
    }

    @PutMapping("/default")
    public R defaultAdd(@RequestBody AddressBook addressBook) {
        addressBook.setIsDefault(0);
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,MyBaseContext.getId());
        addressBookService.update(addressBook,lqw);


        addressBook.setIsDefault(1);
        boolean b = addressBookService.updateById(addressBook);
        if (b) {
            return R.success(addressBook);
        }
        return R.error("保存失败");
    }

    @GetMapping("/default")
    public R getDefault(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,MyBaseContext.getId()).eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(lqw);
        return R.success(addressBook);
    }


    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {

            return R.success(addressBook);
        }
        return R.error("没查到该地址");
    }
    @PutMapping
    public R update(@RequestBody AddressBook addressBook){
        boolean b = addressBookService.updateById(addressBook);
        if (b) {
            return R.success(addressBook);
        }
        return R.error("修改失败");
    }

}
